package com.dao.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.log4j.Logger;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;
import net.sf.json.JSONObject;

import com.bean.ContentPoint;
import com.dao.ContentPointDao;
import com.util.DateUtil;
import com.util.LoggerUtil;

@Component
public class ContentPointDaoImpl implements ContentPointDao {

	public static Logger logger=Logger.getLogger(ContentPointDaoImpl.class);
	@Autowired
	private MongoTemplate mongoTemplate;
	
	
	@Override
	public Map<String, Object> insertContentPoint(String mId, String lId,String type,String deviceType,
			JSONObject logs) {
		Map<String, Object> map=new HashMap<>();
		try {
			Query query = new Query(Criteria.where("mId").is(new ObjectId(mId)).and("lId").is(new ObjectId(lId)).and("type").is(type).and("deviceType").is(deviceType));
			long count = mongoTemplate.count(query, ContentPoint.class);
			if (count > 0) {
				Update update = new Update();
				update.inc("count",1);
				mongoTemplate.updateFirst(query, update, ContentPoint.class);
				map.put("code", "107");
			} else {
				ContentPoint point=new ContentPoint(new ObjectId(lId), new ObjectId(mId),type,DateUtil.formatDateToStrAll(new Date()),deviceType);
				mongoTemplate.insert(point);
				map.put("code", "0");
			}
			LoggerUtil.backlogsSuccess(logs, logger);
		} catch (Exception e) {
			e.printStackTrace();
			map.put("code", "101");
			LoggerUtil.backlogsFalseError(logs, logger,e);
			return map;
		}
		return map;
	}

	@Override
	public Map<String, Object> countContentPoint(String lId, String type,String deviceType,JSONObject logs) {
		Map<String, Object> map=new HashMap<>();
		try {
			Query query = new Query(Criteria.where("lId").is(new ObjectId(lId)).and("type").is(type).and("deviceType").is(deviceType));
			long count = mongoTemplate.count(query, ContentPoint.class);
			map.put("count", count);
			map.put("result", "success");
			LoggerUtil.backlogsSuccess(logs, logger);
		} catch (Exception e) {
			e.printStackTrace();
			map.put("code", "101");
			LoggerUtil.backlogsFalseError(logs, logger,e);
			return map;
		}
		return map;
	}

}
